package com.erebus.media.api;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.erebus.media.mapper.VideosMapper;
import com.erebus.media.model.dto.VideoDto;
import com.erebus.media.model.po.Videos;
import com.erebus.media.service.VideosService;
import com.taobao.base.model.RestResponse;
import io.minio.MinioClient;
import io.minio.ObjectWriteResponse;
import io.minio.PutObjectArgs;
import io.minio.errors.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.StandardCharsets;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.List;
import java.util.stream.Collectors;

@RestController
@CrossOrigin
public class MediaController {

    @Autowired
    MinioClient minioClient;
    @Autowired
    private VideosService videosService;
    @Autowired
    private VideosMapper videosMapper;
    //存储视频
    @Value("${minio.bucket.videofiles}")
    private String bucket_video;

    /**
     * 文件上传
     */
    @PostMapping("/upload")
    public RestResponse<String> upload(@RequestBody byte[] fileData, HttpServletRequest request) throws IOException, ServerException, InsufficientDataException, ErrorResponseException, NoSuchAlgorithmException, InvalidKeyException, InvalidResponseException, XmlParserException, InternalException {
        String fileNameHeader = request.getHeader("X-File-Name");
        String originalFilename = fileNameHeader != null ? java.net.URLDecoder.decode(fileNameHeader, StandardCharsets.UTF_8.name()) : "uploaded_file";
        // 获取当前日期时间并格式化
        LocalDateTime now = LocalDateTime.now();
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyyMMddHHmmss");
        String formattedDate = now.format(formatter);
        // 构造新的文件名
        String newFileName = formattedDate + "-" + originalFilename;
        // 将 byte[] 转换为 InputStream
        InputStream inputStream = new ByteArrayInputStream(fileData);

        // 上传文件到 MinIO
        ObjectWriteResponse or = minioClient.putObject(
                PutObjectArgs.builder()
                        .bucket("taobao") // 替换为你的 MinIO 存储桶名称
                        .object("video/" + newFileName)
                        .stream(inputStream, fileData.length, -1)
                        .contentType("application/octet-stream")
                        .build()
        );
        // todo: 写入数据库
        Videos videos = new Videos();
        videos.setTitle(newFileName);
        videos.setSrc("http://103.36.222.137:9000/taobao/video/" + newFileName);
        videos.setUploadTime(LocalDateTime.now());
        videos.setUserId(1);
        videos.setViewCount(1);
        videosMapper.insert(videos);
        // 返回文件的 URL
        return RestResponse.success("http://103.36.222.137:9000/taobao/" + newFileName);
    }

    // 获取视频列表
    @GetMapping("/videoList")
    public RestResponse<List<VideoDto>> getVideoList() {
        // 构建查询条件
        QueryWrapper<Videos> queryWrapper = new QueryWrapper<>();
        // 查询所有
        List<Videos> videosList = videosMapper.selectList(queryWrapper);
        // 转换为 VideoDto 列表
        List<VideoDto> videoDtoList = videosList.stream().map(video -> {
            VideoDto videoDto = new VideoDto();
            videoDto.setId(video.getVideoId());
            videoDto.setSrc(video.getSrc());
            // 注意：别忘了返回 videoDto
            return videoDto;
        }).collect(Collectors.toList());
        return RestResponse.success(videoDtoList);


    }


    @PostMapping("/test")
    public RestResponse<String> test(HttpServletRequest request) {

        System.out.println(request);

        return RestResponse.success("上传成功");
    }


}
